#!/bin/ash -efu
#
# mki-scripts
#
# This file is part of mkimage
# Copyright (C) 2007-2009  Alexey Gladkov <gladkov.alexey@gmail.com>
#
# This file is covered by the GNU General Public License,
# which should be included with mkimage as the file COPYING.
#

. "${0%/*}"/mki-sh-functions
. shell-quote

verbose "has started executing."

case "$PROG" in
	*-image-*)
		scriptdir="${MKI_IMAGE_SCRIPTDIR:?Script directory required}"
		dir="$subdir"
		;;
	*)
		scriptdir="${MKI_SCRIPTDIR:?Script directory required}"
		;;
esac

if [ ! -d "$scriptdir" ]; then
	verbose "$scriptdir: not found ... ignoring!"
	exit 0
fi

[ -d "$dir/chroot" ] ||
	fatal "$dir: not look like a hasher work directory."

addenv() {
	verbose "Translate variables from Makefile to scripts:"
	printenv |
		sed -ne 's/^\(\(GLOBAL\|INFO\)_[^=]\+\)=/\1\t/p' |
	while read n v; do
		verbose "export $n='$v'"
		printf 'export %s="%s"\n' "$n" "$(quote_shell "$v")"
	done
}

make_exec "$dir/chroot/.host/start.sh" <<EOF
#!/bin/sh -efu
$(addenv)
export WORKDIR=/.image
/.host/script.sh
EOF

find "$scriptdir/" -mindepth 1 -maxdepth 1 -type f -o -type l |
	sort -n |
while read script; do
	[ -x "$script" ] || continue

	case "$script" in
		*~|*.bak|*.rpmnew|*.rpmsave) continue ;;
	esac

	cp -f -- "$script" "$dir/chroot/.host/script.sh"
	chmod 755 -- "$dir/chroot/.host/script.sh"

	verbose "Run: \`$script'"

	env WORKDIR="$dir" \
		mki-run "/.host/start.sh" ||
			fatal "$script: unable to run script."
done

cd "$dir/chroot/.host"
rm -rf -- "start.sh" "script.sh"
